'use strict'

const Controller = require('egg').Controller
const Http = require('http')

class ContactController extends Controller {
  async create() {
    const { ctx, config } = this
    const { phoneNo, email, name, feedback } = ctx.request.body
    const create = {
      phoneNo,
      email,
      name,
      feedback
    }

    await ctx.model.Contact.create(create)
    ctx.body = create

    const title = `New content: ${name}`
    const body = `
      NAME: ${name} <br />
      PHONE NO: ${phoneNo} <br />
      EMAIL: ${email} <br />
      FEEDBACK: ${feedback}
    `
    const { sendcloud } = config
    const param = {
      apiUser: sendcloud.apiUser,
      apiKey: sendcloud.apiKey,
      from: sendcloud.from,
      fromName: 'YC AUTO GROUP',
      subject: title,
      to: 'xank@qq.com',
      html: body
    }

    const data = require('querystring').stringify(param)
    const options = {
      host: 'api.sendcloud.net',
      port: 80,
      path: '/apiv2/mail/send',
      method: 'POST'
    }

    options.path = options.path + '?' + data

    const req = Http.request(options, function(res) {
      let responseStr = ''
      res.on('data', function(chunk) {
        responseStr += chunk
      })
      res.on('end', function() {
        console.log(responseStr)
      })
    })

    req.end()
  }

  async delete() {
    const { ctx } = this
    const { id } = ctx.params
    await ctx.model.Contact.destroy({
      where: {
        id
      }
    })
    ctx.body = { id }
  }

  async update() {
    const { ctx } = this
  }

  async list() {
    const { ctx } = this
    const list = await ctx.model.Contact.findAll()

    ctx.body = {
      list
    }
  }
}

module.exports = ContactController
